from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import HttpResponse
from xadmin.service import xadmin


class API_view(APIView):
    def get(self, request):
        ret = {"code":4000}
        model_list = xadmin.site._registry
        app_conf = []
        for model, admin_class_obj in model_list.items():
            app_name = model._meta.app_label  # app名字
            model_name = model._meta.model_name  # 模型名字
            chi_app_name = model._meta.app_config.verbose_name
            chi_model_name = model._meta.verbose_name

            key = True  # 用来判断

            if not app_conf:
                app_conf.append({
                    "app_info": {"eng_name": app_name, "chi_name": chi_app_name},
                    "label_info": [
                        {"eng_name": model_name, "chi_name": chi_model_name}
                    ]
                })
                continue

            for item in app_conf:
                if app_name == item["app_info"]["eng_name"]:
                    item["label_info"].append({"eng_name": model_name, "chi_name":chi_model_name})
                    key = False

            if key:
                app_conf.append({
                    "app_info":{"eng_name":app_name, "chi_name":chi_app_name},
                    "label_info":[
                        {"eng_name":model_name, "chi_name":chi_model_name}
                    ]
                })
        ret["code"] = 2000
        ret["app_conf"] = app_conf
        return Response(ret)

"""
model._meta.app_config.verbose_name


[
  {
      "app_info": {"eng_name":"SCHOOL", "chi_name": "学校"},
      "label_info": [
          {"eng_name":"STUDENT", "chi_name": "学生信息"},
          {"eng_name":"COLLEGE", "chi_name": "学院信息"}
      ]
  },
  {
      "app_info": {"eng_name":"USER", "chi_name": "用户信息"},
      "label_info": [
          {"eng_name":"NAME", "chi_name": "学生姓名"},
          {"eng_name":"AGE", "chi_name": "学生年龄"},
          {"eng_name":"CLASS", "chi_name": "学生班级"}
      ]
  }
]
"""
# --------------------------删除函数


class DeleteView(APIView):
    def get(self, request, id):
        ret = {"code": 2000, "msg": "删除试图"}
        need_label_name = request.GET.get("label_name")
        need_app_name = request.GET.get("app_name")
        for model, admin_class_obj in xadmin.site._registry.items():

            app_name = model._meta.app_label       # app名字
            model_name = model._meta.model_name   # 模型名字

            if app_name == need_app_name and model_name == need_label_name:
                model.objects.filter(pk=id).delete()
                ret["code"] = 2000
                ret["msg"] = "删除成功"
                return Response(ret)

        return Response(ret)
    # def post(self, request, id):
